﻿using Markdig;

namespace KnownCMS;

class CacheInfo
{
	public DateTime Time { get; set; }
	public string Html { get; set; }
}

/// <summary>
/// 内容系统效用类。
/// </summary>
public class CmsUtils
{
	internal static Dictionary<string, CacheInfo> CachedPosts = [];

	/// <summary>
	/// 将Markdown文本转换成HTML文本，有缓存取缓存。
	/// </summary>
	/// <param name="info">内容明细信息。</param>
	/// <returns>HTML文本。</returns>
	public static MarkupString GetMarkdownHtml(IContentInfo info)
	{
		if (info == null || string.IsNullOrWhiteSpace(info.Id))
			return new MarkupString("");

		var html = string.Empty;
		if (CachedPosts.ContainsKey(info.Id))
		{
			var item = CachedPosts[info.Id];
			if (item.Time < info.PublishTime)
			{
				item.Html = GetHtml(info.Content);
				CachedPosts[info.Id] = item;
			}
			html = item.Html;
		}
		else
		{
			html = GetHtml(info.Content);
			CachedPosts[info.Id] = new CacheInfo { Time = info.PublishTime, Html = html };
		}
		return new MarkupString(html);
	}

	/// <summary>
	/// 将Markdown文本转换成HTML文本。
	/// </summary>
	/// <param name="markdown">Markdown文本。</param>
	/// <returns>HTML文本。</returns>
	public static MarkupString GetMarkdownHtml(string markdown)
	{
		if (string.IsNullOrWhiteSpace(markdown))
			return new MarkupString("");

		var html = GetHtml(markdown);
		return new MarkupString(html);
	}

	private static string GetHtml(string markdown)
	{
		var pipelineBuilder = new MarkdownPipelineBuilder()
			.UsePipeTables()
			.UseBootstrap();
		pipelineBuilder.UseAdvancedExtensions();
		var pipeline = pipelineBuilder.Build();
		return Markdown.ToHtml(markdown, pipeline);
	}

	internal static string GetSearchSummary(string summary, string key)
	{
		// 获取含搜索关键字的摘要字符串
		var text = FormatSearchString(summary);
		if (text.Length <= 100)
			return text;

		if (string.IsNullOrWhiteSpace(key))
			return text.Substring(0, 100);

		var item = string.Empty;
		var keys = key.Split(' ');
		for (int i = 0; i < keys.Length; i++)
		{
			if (string.IsNullOrWhiteSpace(keys[i]))
				continue;

			var index = text.IndexOf(keys[i]);
			if (index >= 0)
			{
				var start = Math.Max(0, index - 100);
				var length = Math.Min(200, text.Length - start);
				item = text.Substring(start, length);
				break;
			}
		}

		return item;
	}

	internal static string GetSearchHtml(string key, string text)
	{
		if (string.IsNullOrWhiteSpace(key))
			return text;

		var keys = key.Split(' ');
		foreach (var item in keys)
		{
			if (string.IsNullOrWhiteSpace(item))
				continue;
			// 高亮显示搜索关键字
			text = text.Replace(item, $"<code>{item}</code>");
		}
		return text;
	}

	private static string FormatSearchString(string text)
	{
		// 替换调影响HTML的字符
		return text.Replace("#", "").Replace("*", "")
				   .Replace("[", "").Replace("]", "")
				   .Replace("<", "").Replace(">", "")
				   .Replace("-", "").Replace("`", "");
	}
}